package com.xuln.attach.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.xuln.common.config.SystemConfig;
import com.xuln.common.util.CommonUtil;
import com.xuln.framework.action.BaseAction;

public class ActtchAction extends BaseAction {
	private static final long serialVersionUID = 742082017999067700L;
	private File[] files;
	private String[] fileName;

	public String uploadImages() throws Exception {
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				String allowedUploadImageExtension = getSystemConfig().getAllowedUploadImageExtension().toLowerCase();
				if (StringUtils.isEmpty(allowedUploadImageExtension)) {
					addActionError("不允许上传图片文件!");
					return ERROR;
				}
				String[] imageExtensionArray = allowedUploadImageExtension.split(SystemConfig.EXTENSION_SEPARATOR);
				String logoExtension = StringUtils.substringAfterLast(fileName[i], ".").toLowerCase();
				if (!ArrayUtils.contains(imageExtensionArray, logoExtension)) {
					addActionError("只允许上传图片文件类型: " + allowedUploadImageExtension + "!");
					return ERROR;
				}
				int uploadLimit = getSystemConfig().getUploadLimit() * 1024;
				if (uploadLimit != 0 && files[i].length() > uploadLimit) {
					addActionError("文件大小超出限制!最大允许" + uploadLimit + "KB");
					return ERROR;
				}
				File uploadImageDir = new File(ServletActionContext.getServletContext().getRealPath(
						SystemConfig.UPLOAD_IMAGE_DIR));
				if (!uploadImageDir.exists()) {
					uploadImageDir.mkdirs();
				}
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
				String dateString = simpleDateFormat.format(new Date());
				String uploadImagePath = SystemConfig.UPLOAD_IMAGE_DIR + dateString + "/" + CommonUtil.getUUID() + "."
						+ logoExtension;
				File file = new File(ServletActionContext.getServletContext().getRealPath(uploadImagePath));
				FileUtils.copyFile(files[i], file);
			}
		}
		return null;
	}
}
